<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件

//商品过期时间 30 天
//define('__PASS_TIME__',30*86400);

//好货推荐所需打赏金额
define('__GOOD_AMOUNT__',1.00);

//qq登录创建账户默认密码
define('__DEFAULT_PWD__',123456);

/**
 * 生成待请求字符串
 * @param $paramArr
 * @param bool|true     $sort       是否排序           默认排序
 * @param bool|false    $encode     是否urlencode处理  默认不处理
 * @param bool|false    $isnull     是否过滤空值字段   默认不过滤
 * @param string|&      $str        链接字符           默认&
 * @return string 返回待签字符串
 */
function createSignStr ($paramArr, $sort = false, $encode = false, $isnull = false, $str = '&') {
    $param_array   = array();
    if($sort){
        ksort ( $paramArr );
        reset ( $paramArr );
    }
    foreach ($paramArr as $key => $val) {
        //$val = mb_convert_encoding($val,"GBK", "UTF-8");
        if($isnull){
            if($val === ''){
                unset($paramArr[$key]);
            }else{
                if($encode){
                    $param_array[] = $key.'='.urlencode($val);
                }else{
                    $param_array[] = $key.'='.$val;
                }
            }
        }else{
            if($encode){
                $param_array[] = $key.'='.urlencode($val);
            }else{
                $param_array[] = $key.'='.$val;
            }
        }
    }
    $param_str  = implode($str,$param_array);
    return $param_str;
}


/**
 * url参数转化成数组
 */
function convertUrlArray($query) {
    $queryParts = explode('&', $query);
    $params = array();
    foreach ($queryParts as $param) {
        $item = explode('=', $param);
        $params[$item[0]] = urldecode($item[1]);
    }
    return $params;
}

/**
 * 发送请求
 * @param $opts     //已加密字符串
 * @param $url      //发送地址
 * @return mixed    //返回支付返回信息
 */
function sendHttpRequest($opts, $url) {
    $ch     = curl_init ();
    curl_setopt ( $ch, CURLOPT_URL, $url );
    curl_setopt ( $ch, CURLOPT_POST, 1 );
    curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, false);//不验证证书
    curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, false);//不验证HOST
    curl_setopt ( $ch, CURLOPT_SSLVERSION, 1);
    curl_setopt ( $ch, CURLOPT_POSTFIELDS, $opts );
    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
    // 运行cURL，请求网页
    $html = curl_exec ( $ch );
    curl_close ( $ch );
    return $html;
}

/*
 * 验证手机号正确
 * @param $phone
 * @return bool
 */
function plum_is_phone($phone) {
    $pattern = '/^1(\d{10})$/';
    if (preg_match($pattern, $phone)) {
        return true;
    }
    return false;
}

/*
 * 验证是否为邮箱
 * @param $email
 * @return bool
 */
function plum_is_email($email) {
    $pattern = '/^[A-Za-z0-9]+([-_\.][A-Za-z0-9]+)*@([A-Za-z0-9]+[-\.])+[A-Za-z0-9]{2,5}$/i';
    if (preg_match($pattern, $email)) {
        return true;
    }
    return false;
}

/*
 * 对手机号进行掩码处理
 * 手机号掩码的规则是末尾4位，开头余数位不变，中间4的整数倍字符用星号替换
 */
function plum_format_mobile($mobile)
{
    //颠倒顺序每隔4位分割为数组
    $split = str_split(strrev($mobile),4);
    //头和尾保留，其他部分替换为星号
    $split = array_fill(1,count($split) - 2,"****") + $split;
    ksort($split);        //合并颠倒顺序
    return strrev(implode("",$split));
}

/*
 * Notes:发送邮件相关配置
 * @time: 2019/9/12 0012 16:04
 * @author YeWenHao
 */
function sendEmail($info = [])
{
    Vendor('phpmailer.phpmailer');
    $mail = new \phpmailer\PHPMailer(); //实例化

    $mail->IsSMTP(); // 启用SMTP
    $mail->Host       = 'smtp.qq.com'; //SMTP服务器 以QQ邮箱为例子
    $mail->Port       = 465;  //邮件发送端口
    $mail->SMTPAuth   = true;  //启用SMTP认证
    $mail->SMTPSecure = "ssl";   // 设置安全验证方式为ssl

    $mail->CharSet    = "UTF-8"; //字符集
    $mail->Encoding   = "base64"; //编码方式

    $mail->Username   = '1298025852@qq.com';  //你的邮箱
    $mail->Password   = 'sjcqykfjechhbaed';    //密码/授权码
    $mail->Subject    = '校内二手物品交易平台'; //邮件标题

    $mail->From       = '1298025852@qq.com';  //发件人地址（也就是你的邮箱）
    $mail->FromName   = '淘二货';  //发件人姓名

    if ($info && is_array($info)){
        $mail->AddAddress($info['to_email'], "尊敬的用户"); //添加收件人（地址，昵称）
        $mail->IsHTML(true); //支持html格式内容
        $mail->Body = $info['content']; //邮件主体内容

        //发送
        if ($mail->Send()) {
            return true;
        } else {
            return false;
        }
    }
}

/*
 * 生成需要长度的随机验证码
 */
function make_Verification_Code($length)
{
    // 密码字符集，可任意添加你需要的字符
    $chars = array('0', '1', '2', '3',
		'4', '5', '6', '7', '8', '9',
        );
    // 在 $chars 中随机取 $length 个数组元素键名
    $keys = array_rand($chars, $length);
    $password = '';
    for($i = 0; $i < $length; $i++)
    {
        // 将 $length 个数组元素连接成字符串
        $password .= $chars[$keys[$i]];
    }
    return $password;
}

/*
 * 判断是否为邮箱或手机号
 */
function isEmailOrPhone($str)
{
    $preg_email='/^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@([a-zA-Z0-9]+[-.])+([a-z]{2,5})$/ims';
    if(preg_match($preg_email,$str)){
        return 'email';
    }else{
        $preg_phone='/^1[34578]\d{9}$/ims';
        if(preg_match($preg_phone,$str)){
            return 'phone';
        }
    }
}

/*
 * 统一接口数据返回 json
 */
function displayJson($data)
{
    return json_encode($data,JSON_UNESCAPED_UNICODE);
}

/**
 *拒绝访问 统一封装
 */
function refuseVisit()
{
    $info['code']    = '400';
    $info['message'] = '拒绝访问';
    return displayJson($info);
}


/*
* 将流文件保存为临时文件
* @param   stream  base64输入流
* @param   tmpname 临时文件路径
*/
function uploadBase64($stream) {
    if (empty($stream)) return false;
    if (preg_match('/^(data:(\s)?(image|img)\/(\w+);base64,)/', $stream, $str)) {
        $suffix = "tmp";
        $tmpname = rand(1000, 9999) . ".{$suffix}";
        if (file_put_contents($tmpname, base64_decode(str_replace($str[1], '', $stream)))) {
            return $tmpname;
        } else {
            return false;
        }
    } else {
        return false;
    }
}

/*
获取图片真实后缀
@param   filename    文件名
@param   suffix      文件真实后缀（.jpg .png .gif）
*/
function getSuffix($fileName)
{
    $file = fopen($fileName, "rb");
    $bin = fread($file, 2); // 只读2字节
    fclose($file);
    $strInfo = @unpack("C2chars", $bin);
    $typeCode = intval($strInfo['chars1'] . $strInfo['chars2']);
    $suffix = "unknow";
    if($typeCode == 255216){
        $suffix = "jpg";
    }elseif($typeCode == 7173){
        $suffix = "gif";
    }elseif($typeCode == 13780){
        $suffix = "png";
    }elseif($typeCode == 6677){
        $suffix = "bmp";
    }elseif($typeCode == 7798){
        $suffix = "exe";
    }elseif($typeCode == 7784){
        $suffix = "midi";
    }elseif($typeCode == 8297){
        $suffix = "rar";
    }elseif($typeCode == 7368){
        $suffix = "mp3";
    }elseif($typeCode == 0){
        $suffix = "mp4";
    }elseif($typeCode == 8273){
        $suffix = "wav";
    }
    return $suffix;
}

/**
 * desription 判断是否gif动画
 * @param sting $image_file图片路径
 * @return boolean t 是 f 否
 */
function check_gifcartoon($image_file){
    $fp = fopen($image_file,'rb');
    $image_head = fread($fp,1024);
    fclose($fp);
    return preg_match("/".chr(0x21).chr(0xff).chr(0x0b).'NETSCAPE2.0'."/",$image_head)?false:true;
}

/**
 * desription 压缩图片
 * @param sting $imgsrc 图片路径
 * @param string $imgdst 压缩后保存路径
 * * @param int $quality 图片质量
 */
function compressed_image($imgsrc,$imgdst, $quality){
    list($width,$height,$type)=getimagesize($imgsrc);

    //这里如果写的是图片大小不变 如果要改变图片大小，如:$new_width = $width * 0.5; 宽度减少一半
    $new_width = $width;
    $new_height =$height;
    switch($type){
        case 1:
            $giftype = check_gifcartoon($imgsrc);
            if($giftype){
                header('Content-Type:image/gif');
                $image_wp=imagecreatetruecolor($new_width, $new_height);
                $image = imagecreatefromgif($imgsrc);
                imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
                //$quality代表的是质量、压缩图片容量大小
                imagejpeg($image_wp, $imgdst,$quality);
                imagedestroy($image_wp);
            }
            break;
        case 2:
            header('Content-Type:image/jpeg');
            $image_wp=imagecreatetruecolor($new_width, $new_height);
            $image = imagecreatefromjpeg($imgsrc);
            imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
            //$quality代表的是质量、压缩图片容量大小
            imagejpeg($image_wp, $imgdst,$quality);
            imagedestroy($image_wp);
            break;
        case 3:
            header('Content-Type:image/png');
            $image_wp=imagecreatetruecolor($new_width, $new_height);
            $image = imagecreatefrompng($imgsrc);
            imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
            //$quality代表的是质量、压缩图片容量大小
            imagejpeg($image_wp, $imgdst,$quality);
            imagedestroy($image_wp);
            break;
    }


    function getImgMsg($imageFileName,$file_type,$pic_width_max,$pic_height_max,$uploadfile_resize)
    {
        if($file_type == "image/pjpeg"||$file_type == "image/jpg"|$file_type == "image/jpeg"){
            $im = imagecreatefromjpeg($imageFileName);
        }else if($file_type == "image/x-png"){
            $im = imagecreatefromjpeg($imageFileName);
        }else if($file_type == "image/gif"){
            $im = imagecreatefromjpeg($imageFileName);
        }else {//默认jpg
            $im = imagecreatefromjpeg($imageFileName);
        }
        if($im) {
            resizeImage($im, $pic_width_max, $pic_height_max, $uploadfile_resize);
            ImageDestroy($im);
        }
    }




    function resizeImage($uploadfile,$maxwidth,$maxheight,$filename){
//取得当前图片大小
        $width = imagesx($uploadfile);
        $height = imagesy($uploadfile);

        //压缩比值
        $i=0.5;
        //生成缩略图的大小
        if(($width > $maxwidth) || ($height > $maxheight)){
            $newwidth = $width * $i;
            $newheight = $height * $i;
            if(function_exists("imagecopyresampled")){
                $uploaddir_resize = imagecreatetruecolor($newwidth, $newheight);
                //echo $uploaddir_resize;
                imagecopyresampled($uploaddir_resize, $uploadfile, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
            }else{
                $uploaddir_resize = imagecreate($newwidth, $newheight);
                imagecopyresized($uploaddir_resize, $uploadfile, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
            }

            ImageJpeg ($uploaddir_resize,$filename);
            ImageDestroy ($uploaddir_resize);
        }else{
            ImageJpeg ($uploadfile,$filename);
        }
    }



}

